package seedpod.model;
/**
 * Copyright 2009 University of  Washington
 * This code is released under the GPL version 3 - with a copy of the license included
 * @author Maya Hao Li
 *
 * retrieves a set of data objects.
 */
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import seedpod.exceptions.SeedpodException;
import seedpod.kb2db.ClsMap;
import seedpod.rdb.PManager;
import seedpod.rdb.RdbSql;


public class DataObjectSet {
	private ArrayList<SeedpodDO> _doSet;
	private String _classType;
	private PManager _manager;

	public DataObjectSet(String classType, PManager manager) {
		_classType = classType;
		_manager = manager;
	}

	
	/**
	 * Returns a set of Seedpod Data objects with limits added by the query filter 
	 * @param queryFilter
	 * @return
	 * @throws SeedpodException
	 */
	public ArrayList<SeedpodDO> query( String queryFilter ) throws SeedpodException {
		ClsMap cmap = _manager.getModelMap().getClsMap( _classType );
		
		if ( cmap == null  ) {
			throw new SeedpodException("query object set can't find _classType " + _classType); 
		}
		
		ResultSet rs;
		SeedpodDO tmpObj;
		_doSet = new ArrayList<SeedpodDO>();

		String query = RdbSql.selectSql( cmap.getName(), null, queryFilter ).toString();

		// execute query
		try {
			rs = _manager.getRdbConnection().executeQuery( query.toString () );

			if ( rs != null ) {
				while (rs.next() ) {
					tmpObj = (SeedpodDO)_manager.createObject(  _classType );
					tmpObj.load( rs );
					_doSet.add( tmpObj );
				}
			}
		}
		catch (SQLException e) {
			e.printStackTrace();
//			throw new SeedpodException( e, "retrieve() error: " + query.toString() );
		}
		return _doSet;
	}
	
	/**
	 * Returns the latest set of data objects specified by lastLimit
	 * @param lastLimit
	 * @return
	 * @throws SeedpodException 
	 */
	public ArrayList<SeedpodDO> query(int lastLimit) throws SeedpodException {
		return query(  "LIMIT " + lastLimit );
	}
	

}
